package com.sen.design.pattern.creational.singleton;

import java.io.Serializable;

/**
 * 饿汉式（线程安全）：如果一直用不到单例类，可能造成内存浪费，
 */
public class HungrySingleton implements Serializable,Cloneable {
    // 静态成员变量
    //    private final static HungrySingleton HUNGRY_SINGLETON = new HungrySingleton();
    private final static HungrySingleton HUNGRY_SINGLETON;

    // 静态代码块初始化
    static {
        HUNGRY_SINGLETON = new HungrySingleton();
    }

    private HungrySingleton() {
        if (HUNGRY_SINGLETON != null){
            throw new RuntimeException("单例模式构造器禁止反射调用");
        }
    }

    public static HungrySingleton getInstance() {
        return HUNGRY_SINGLETON;
    }

    private Object readResolve(){
        return HUNGRY_SINGLETON;
    }

    /**
     * 防止原型模式破坏单例
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return getInstance();
    }
}
